<?php

namespace app\api\controller;

use app\BaseController;
use app\api\model\Sms as SmsModel;
use app\api\model\User as UserModel;
use app\lib\tool\Str;
use app\lib\sms\Alisms;
use think\facade\Cache;
use app\api\model\Favorite as FavoriteModel;
use app\api\model\View as ViewModel;
use app\api\model\Suggest as Suggest;
use app\api\model\Contribute as ContributeModel;

class User extends BaseController
{
    public function initialize()
    {
        $this->uid = $this->request->uid;
    }

    /* 发送短信 */
    public function sendSms()
    {
        $phone = input('phone', '');
        $code = mt_rand(1000, 9999);
        $result = Alisms::sendCode($phone, 'SMS_210070656', $code);
        if ($result) {
            SmsModel::create([
                'phone' => $phone,
                'code' => $code,
                'status' => 1
            ]);
            return show(200, '短信验证码发送成功');
        } else {
            return show(config('status.sms_send_fail'), '短信验证码发送失败');
        }
    }

    /* 注册 */
    public function register()
    {
        $username = input('username', '');
        $password = input('password', '');
        $repassword = input('repassword', '');
        $code = input('code', '');

        $user = UserModel::where('username', $username)->find();
        if ($user) {
            return show(config('status.register_error'), '注册失败，用户已存在');
        }

        if ($password != $repassword) {
            return show(config('status.password_nosame'), '两次密码输入不一致');
        }

        $sms = SmsModel::where(['phone' => $username, 'code' => $code, 'status' => 1])->find();
        if ($sms) {
            UserModel::create([
                'username' => $username,
                'password' => md5($username . $password),
                'avatar' => 'https://qiniuyun.sxqhkj.com/image/20210421/d0ec05b3f502be212212d6a1b3f6f5a3.png',
                'nickname' => $username,
                'signature' => '我的签名',
                'time' => time()
            ]);

            SmsModel::update([
                'status' => 0
            ], ['phone' => $username, 'code' => $code]);

            return show(200, '注册成功');
        } else {
            return show(config('status.sms_error'), '短信验证码不正确');
        }
    }

    /* 找回密码 */
    public function findPassword()
    {
        $username = input('username', '');
        $password = input('password', '');
        $repassword = input('repassword', '');
        $code = input('code', '');

        $user = UserModel::where('username', $username)->find();
        if (!$user) {
            return show(config('status.find_password_user'), '用户不存在');
        }

        if ($password != $repassword) {
            return show(config('status.password_nosame'), '两次密码输入不一致');
        }

        $sms = SmsModel::where(['phone' => $username, 'code' => $code, 'status' => 1])->find();
        if ($sms) {
            UserModel::update([
                'password' => md5($username . $password)
            ], ['username' => $username]);

            SmsModel::update([
                'status' => 0
            ], ['phone' => $username, 'code' => $code]);

            return show(200, '重置密码成功');
        } else {
            return show(config('status.sms_error'), '短信验证码不正确');
        }
    }

    /* 登录 */
    public function login()
    {
        $username = input('username', '');
        $password = input('password', '');
        $type = input('type', 1, 'intval');
        $openid = input('openid', '');

        if ($type == 1) {
            $user = UserModel::where('username', $username)->find();
            if (!$user) {
                return show(config('status.find_password_user'), '用户不存在');
            }
            $password = md5($username . $password);
            $user = $user->toArray();
            if ($password == $user['password']) {
                $token = $this->getToken($user['id'], $user['username']);
                $data = ['token' => $token];
                return show(200, '登录成功', $data);
            } else {
                return show(config('status.password_error'), '密码错误');
            }
        } else if ($type == 2) {
            $user = UserModel::where('wx', $openid)->find();
            if (!$user) {
                return show(config('status.wx_not_bind'), '该微信暂未绑定账号');
            }
            $token = $this->getToken($user['id'], $user['username']);
            $data = ['token' => $token];
            return show(200, '登录成功', $data);
        } else if ($type == 3) {
            $user = UserModel::where('qq', $openid)->find();
            if (!$user) {
                return show(config('status.qq_not_bind'), '该QQ暂未绑定账号');
            }
            $token = $this->getToken($user['id'], $user['username']);
            $data = ['token' => $token];
            return show(200, '登录成功', $data);
        }
    }

    /* 获取token */
    public function getToken($id, $username)
    {
        $token = Str::getToken('');
        $redisData = [
            'id' => $id,
            'username' => $username
        ];
        Cache::set(config('cache.redis.prefix') . $token, $redisData, 3600 * 24 * 7);
        return $token;
    }

    /* 个人信息 */
    public function info()
    {
        if (!$this->request->auth) return show(config('status.auth'), '认证失败');
        $data = UserModel::where('id', $this->uid)->find();
        $data['view'] = ViewModel::where('uid', $this->uid)->count();
        $data['favorite'] = FavoriteModel::where('uid', $this->uid)->count();
        return show(200, 'success', $data);
    }

    /* 意见反馈 */
    public function suggest()
    {
        if (!$this->request->auth) return show(config('status.auth'), '认证失败');
        $content = input('content', '');
        $data = Suggest::create([
            'uid' => $this->uid,
            'content' => $content,
            'time' => time()
        ]);
        if ($data) {
            return show(200, '意见反馈成功');
        } else {
            return show(config('status.error_add'), '意见反馈失败');
        }
    }

    /* 我的投稿 */
    public function contribute()
    {
        if (!$this->request->auth) return show(config('status.auth'), '认证失败');
        $name = input('name', '');
        $tel = input('tel', '');
        $content = input('content', '');
        $data = ContributeModel::create([
            'uid' => $this->uid,
            'name' => $name,
            'tel' => $tel,
            'content' => $content,
            'time' => time()
        ]);
        if ($data) {
            return show(200, '投稿成功');
        } else {
            return show(config('status.error_add'), '投稿失败');
        }
    }

    /* 修改手机号 */
    public function modifyUsername()
    {
        if (!$this->request->auth) return show(config('status.auth'), '认证失败');
        $username = input('username', '');
        $code = input('code', '');

        $user = UserModel::where('username', $username)->find();
        if ($user) {
            return show(config('status.username_exist'), '账号已存在');
        }

        $sms = SmsModel::where(['phone' => $username, 'code' => $code, 'status' => 1])->find();
        if ($sms) {
            UserModel::update([
                'username' => $username
            ], ['id' => $this->uid]);

            SmsModel::update([
                'status' => 0
            ], ['phone' => $username, 'code' => $code]);
            return show(200, '修改手机号成功');
        } else {
            return show(config('status.sms_error'), '短信验证码不正确');
        }
    }

    /* 修改签名 */
    public function modifySignature()
    {
        if (!$this->request->auth) return show(config('status.auth'), '认证失败');
        $signature = input('signature', '');
        $data = UserModel::update([
            'signature' => $signature
        ], ['id' => $this->uid]);
        if ($data) {
            return show(200, '修改签名成功');
        } else {
            return show(config('status.error_update'), '修改失败');
        }
    }

    /* 修改昵称 */
    public function modifyNickname()
    {
        if (!$this->request->auth) return show(config('status.auth'), '认证失败');
        $nickname = input('nickname', '');
        $data = UserModel::update([
            'nickname' => $nickname
        ], ['id' => $this->uid]);
        if ($data) {
            return show(200, '修改昵称成功');
        } else {
            return show(config('status.error_update'), '修改失败');
        }
    }

    /* 修改密码 */
    public function modifyPassword()
    {
        if (!$this->request->auth) return show(config('status.auth'), '认证失败');
        $oldpassword = input('oldpassword', '');
        $newpassword = input('newpassword', '');
        $repassword = input('repassword', '');

        if ($newpassword != $repassword) {
            return show(config('status.password_nosame'), '两次密码输入不一致');
        }

        $user = UserModel::where('id', $this->uid)->find();
        $user_password = md5($user['username'] . $oldpassword);
        if ($user_password == $user['password']) {
            UserModel::update([
                'password' => md5($user['username'] . $newpassword)
            ], ['id' => $this->uid]);
            return show(200, '密码修改成功');
        } else {
            return show(config('status.password_error'), '原始密码输入错误');
        }
    }

    /* 绑定WX */
    public function bindWX()
    {
        if (!$this->request->auth) return show(config('status.auth'), '认证失败');
        $wx = input('wx', '');
        $wxname = input('wxname', '');
        $wximage = input('wximage', '');
        $data = UserModel::update([
            'wx' => $wx,
            'wxname' => $wxname,
            'wximage' => $wximage
        ], ['id' => $this->uid]);
        if ($data) {
            return show(200, '绑定微信成功');
        } else {
            return show(config('status.error_update'), '绑定微信失败');
        }
    }

    /* 解绑WX */
    public function unbindWX()
    {
        if (!$this->request->auth) return show(config('status.auth'), '认证失败');
        $data = UserModel::update([
            'wx' => '',
            'wxname' => '',
            'wximage' => ''
        ], ['id' => $this->uid]);
        if ($data) {
            return show(200, '解绑微信成功');
        } else {
            return show(config('status.error_update'), '解绑微信失败');
        }
    }

    /* 绑定QQ */
    public function bindQQ()
    {
        if (!$this->request->auth) return show(config('status.auth'), '认证失败');
        $qq = input('qq', '');
        $qqname = input('qqname', '');
        $qqimage = input('qqimage', '');
        $data = UserModel::update([
            'qq' => $qq,
            'qqname' => $qqname,
            'qqimage' => $qqimage
        ], ['id' => $this->uid]);
        if ($data) {
            return show(200, '绑定QQ成功');
        } else {
            return show(config('status.error_update'), '绑定QQ失败');
        }
    }

    /* 解绑QQ */
    public function unbindQQ()
    {
        if (!$this->request->auth) return show(config('status.auth'), '认证失败');
        $data = UserModel::update([
            'qq' => '',
            'qqname' => '',
            'qqimage' => ''
        ], ['id' => $this->uid]);
        if ($data) {
            return show(200, '解绑QQ成功');
        } else {
            return show(config('status.error_update'), '解绑QQ失败');
        }
    }

    /* 上传头像 */
    public function uploadAvatar()
    {
        $file = request()->file('file');
        $savename = \think\facade\Filesystem::disk('qiniu')->putFile('image', $file);
        $savename = str_replace('\\', '/', $savename);

        UserModel::update([
            'avatar' => config('filesystem.disks.qiniu.domain') . '/' . $savename
        ], ['id' => $this->uid]);
        return show(200, '头像上传成功', config('filesystem.disks.qiniu.domain') . '/' . $savename);
    }
}
